<template>
	<div>
		<BreadList :list="['Home','Content',{'name':'About'},'Edit']"></BreadList>
		<a-card>
			<!-- {{editStatus == 0 ? '添加' : '修改'}} -->
			<a-form-model ref="ruleForm" :model="editForm" :rules="rules">
				<a-form-model-item has-feedback label="标题" prop="aboutTitle">
					<a-input v-model="editForm.aboutTitle" type="text" />
				</a-form-model-item>
				<a-form-model-item has-feedback label="内容主体" prop="aboutContent">
					<mavon-editor v-model="editForm.aboutContent" />
				</a-form-model-item>
				<a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
					<a-button type="primary" @click="submitForm('ruleForm')">
						Submit
					</a-button>
					<a-button style="margin-left: 10px" @click="resetForm('ruleForm')">
						Reset
					</a-button>
				</a-form-model-item>
			</a-form-model>
		</a-card>
	</div>
</template>

<script>
	import {
		getAboutById,
		updateAbout,
		addAbout
	} from '@/api/Content.js'
	export default {
		name: 'AboutEdit',
		data() {
			return {
				editStatus: 0,
				about: {},
				editForm: {
					aboutTitle: '',
					aboutContent: ''
				},
				rules: {
					aboutTitle: [{
							required: true,
							message: '请输入标题',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 60,
							message: 'Length should be 3 to 60',
							trigger: 'blur'
						},
					],
					aboutContent: [{
						required: true,
						message: '请输入内容主体',
						trigger: 'blur'
					}]
				},
			}
		},
		created() {
			const aboutId = this.$route.query.aboutId
			// 判断 js 字符串为空
			if (aboutId !== undefined) {
				this.editStatus = 1
				this.getAboutById(aboutId)
			}
		},
		methods: {
			// 修改获得数据填充
			async getAboutById(id) {
				const {
					data: res
				} = await getAboutById(id)
				// console.log(res)
				if (res.code !== 20000)
					return this.$message.error('加载 About 出错')
				this.about = res.data
				this.editForm.aboutTitle = this.about.aboutTitle
				this.editForm.aboutContent = this.about.aboutContent
				this.$message.success(res.msg)
			},
			submitForm(formName) {
				this.$refs[formName].validate(async valid => {
					if (valid) {
						// 修改
						if (this.editStatus === 1) {
							this.about.aboutTitle = this.editForm.aboutTitle
							this.about.aboutContent = this.editForm.aboutContent
							const {data : res} = await updateAbout(this.about)
							if (res.code !== 20008)
								return this.$message.error('修改出错')
							this.$router.push('/content/about')
							this.$message.success(res.msg)
						} else {
							// 添加
							const {data :res} = await addAbout(this.editForm)
							if (res.code !== 20000)
								return this.$message.error('修改出错')
							this.$router.push('/content/about')
							this.$message.success(res.msg)
						}
						
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
		}
	}
</script>

<style>
</style>
